package com.fingard.dsp.bank.directbank.ynht01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;

import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import java.io.File;

public class YNHT01BatPayRec extends YNHT01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {

        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        try {
            YNHT01Header header = headerInit("510003", p_req1988.reqBatchNO);//查证使用批次号
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommonHeader(xmlTextWriter, header);
            xmlTextWriter.writeStartElement("ReqParam");
            xmlTextWriter.writeElementString("TotalNum", p_req1988.totalNum);
            xmlTextWriter.writeElementString("TotalAmt", p_req1988.totalAmt);
            xmlTextWriter.writeElementString("AcctNo", p_req1988.ownAct);
            xmlTextWriter.writeElementString("AcctName", p_req1988.ownActName);
            /**
             * 文件名
             * 支付流水号|!帐号|!转出户名|!转账类型|!转入账号|!转入户名|!转入帐号开户行号|!转入帐号开户行名|!币种|!转账金额|!转入账户类型|!凭证号|!备注
             */
            StringBuilder fileContent = new StringBuilder();
            String separator = "|!";
            while (p_req1988.readRecord()) {
                if(p_req1988.sameBnk.equals("0")){
                    throw new Exception("行内暂时不支持他行转账");
                }
                fileContent.append(p_req1988.readedDetail.askNumber).append(separator)
                        .append(p_req1988.readedDetail.payAct).append(separator)
                        .append(p_req1988.readedDetail.payName).append(separator)
                        .append("1".equals(p_req1988.readedDetail.sameBnk)?"0":"1").append(separator)//0–行内 1-行外  暂时只支持行内转账
                        .append(p_req1988.readedDetail.recAct).append(separator)
                        .append(p_req1988.readedDetail.recName).append(separator)
                        .append(separator)//转入帐号开户行号本行行内填空
                        .append(separator)//转入帐号开户行名本行行内填空
                        .append(convertCurToBank(p_req1988.readedDetail.payCur)).append(separator)
                        .append(p_req1988.readedDetail.payAmount).append(separator)
                        .append(getBankConfig().getMapKeyByValue("CustTypeMapping", p_req1988.readedDetail.isPrivate)).append(separator)//Ats:1：对私 2：对公   行内:0-对私，1-对公
                        .append(p_req1988.abstractATS).append(separator)//凭证号也取对账码
                        .append(p_req1988.readedDetail.purpose);//批量每个单笔的备注取用途字段。
                fileContent.append("\r\n");
            }
            WriteBankLogLn2("批量代收付请求文件内容:\r\n" + fileContent.toString());

            String fileName = p_req1988.reqHeader.bankCode + p_req1988.reqBatchNO + ".txt";
            String tmpLocalFilePath = getTempFileDirectory() + File.separator + fileName;
            WriteBankLogLn2("批量转账录入本地临时文件路径: " + tmpLocalFilePath);

            if (FileHelper.existFile(tmpLocalFilePath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            FileHelper.appendFile(tmpLocalFilePath, fileContent.toString(), getCharset());
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            String ftpUpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + fileName;
            WriteBankLogLn("当日批次文件上传FTP服务器路径:" + ftpUpFilePath);

            SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
            String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + fileName;
            FtpReceiver ftpReceiver = sftpPortClient.uploadFile("", tmpLocalFilePath, sftpFilePath);
            sftpPortClient.disconnect();

            retAts.respCode = "0";
            if (!ftpReceiver.isCompleted) {
                WriteBankLogLn2("sftp连接异常");
                retAts.respCode = "-1";
                retAts.respInfo = ftpReceiver.connMsg;
                retAts.writeRetToATS();
                return retAts;
            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                WriteBankLogLn2("文件上传失败");
                retAts.respInfo = "上传失败";
                retAts.transState = "UploadFailed";
                retAts.payInfoCode = "";
                retAts.writeRetToATS();
                return retAts;
            } else {
                WriteBankLogLn2("文件上传成功,开始发送" + p_req1988.reqHeader.transType + "报文");
                retAts.respInfo = "上传成功";
//                retAts.transState = "UploadSucceed";
//                retAts.payInfoCode = "";
            }
            xmlTextWriter.writeElementString("FileName", fileName);
            xmlTextWriter.writeElementString("CertNo", p_req1988.abstractATS);
            xmlTextWriter.writeElementString("Memo", p_req1988.useType);//批量备注取用途字段。
            xmlTextWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/HTBankData/RspData/RspHead/RspCode");
                    String returnMsg = tmpBkReader.getFirstText("/HTBankData/RspData/RspHead/RspMsg");
                    if ("000000".equals(returnCode)) {
                        /** 通讯响应码 */
                        retAts.respCode = "0";
                        /** 通讯响应信息 */
                        retAts.respInfo = returnMsg;
                        /** 支付状态 */
                        retAts.transState = returnCode;
                        /** 支付信息码 */
                        retAts.payInfoCode = returnCode;
                        /** 支付批次号 */
                        retAts.reqSeqID = p_req1988.reqBatchNO;
                        /** 新支付批次号 */
                        retAts.newReqSeqID = "";
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = returnMsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception ex) {
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        YNHT01Header header = headerInit("510004", p_req1998.reqBatchNO);
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommonHeader(xmlTextWriter, header);
            xmlTextWriter.writeStartElement("ReqParam");
            xmlTextWriter.writeElementString("AcctNo", p_req1998.ownAct);
            xmlTextWriter.writeElementString("OldTermDate", DateHelper.convertD10toD8(Format.DateTimeFormat.format(p_req1998.getBgnDateTime())));
            xmlTextWriter.writeElementString("OldSeqNo", p_req1998.reqBatchNO);
            xmlTextWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlTextWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/HTBankData/RspData/RspHead/RspCode");
                    String returnMsg = tmpBkReader.getFirstText("/HTBankData/RspData/RspHead/RspMsg");
                    if ("000000".equals(returnCode)) {
                        String totalNum = tmpBkReader.getFirstText("/HTBankData/RspData/Result/TotalNum");
                        String totalAmt = tmpBkReader.getFirstText("/HTBankData/RspData/Result/TotalAmt");
                        String tmpDownFileName = tmpBkReader.getFirstText("/HTBankData/RspData/Result/FileName");
                        String tmpLocalMarkPath = createTempFileDirectory() + File.separator +"bat";
                        File mdDir = new File(tmpLocalMarkPath);
                        if (!mdDir.exists()) {
                            mdDir.mkdirs();
                        }
                        WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);

                        FtpSet ftpSet = bankFront.getFtpSet("bat");
                        String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + tmpDownFileName;
                        WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                        FtpReceiver ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, tmpLocalMarkPath);
                        sftpPortClient.disconnect();
                        if (ftpReceiver.isCompleted) {
                            String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath+File.separator + tmpDownFileName, ftpSet.charset);
                            WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                            if (StringHelper.hasAnyChar(tmpStrRet)) {
                                retAts.respCode = "0";
                                retAts.reqSeqID = p_req1998.reqBatchNO;
                                int readedLine = 0;
                                String[] transDetailArr = tmpStrRet.split("\\n");
                                for (String tranInfo : transDetailArr) {
                                    tranInfo = tranInfo+"+";
                                    String[] bodyValues = tranInfo.split("\\|!");
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    String seqNo = bodyValues[1];
                                    String acctNo = bodyValues[3];
                                    String amount = bodyValues[4];
                                    String tranStatus = bodyValues[5];//0-待审核1-审核拒绝2-交易成功3-交易失败4-未知5-重复支付
                                    String tranStatusDesc = bodyValues[6];
                                    tmpRetDetail.payAct = acctNo;
                                    tmpRetDetail.payAmount = amount;
                                    tmpRetDetail.postScript = seqNo;
                                    tmpRetDetail.result = tranStatus;
                                    tmpRetDetail.payInfoCode = tranStatus;
                                    if (!StringHelper.isNullOrEmpty(tranStatusDesc))
                                        tmpRetDetail.memo = "交易状态说明:" + tranStatusDesc;
                                    retAts.writeRetDetail(tmpRetDetail);
                                    readedLine++;
                                }
                                if (!retAts.respCode.equals("-1") && Integer.parseInt(totalNum) != readedLine) {
                                    WriteBankLogLn("文件所含笔数与报文提示笔数不一致");
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "本地批次结果文件内容为空!";
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "批次结果文件下载失败:" + ftpReceiver.connMsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = returnMsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

}
